import React from "react";
import {Popconfirm, DatePicker,Spin, Modal, Table, Button, Tag, Form, Input} from 'antd';
import { closeStatus} from "../../store/action";
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import API from '../../api/api'
import InsertFormForActivity from './InsertFormForActivity'
import UpdateFormForActivity from './UpdateFormForActivity'
import { DownloadOutlined} from '@ant-design/icons';
import './Activity.css'
import {Link} from "react-router-dom";
const {RangePicker} = DatePicker
var downLoadIcon = <DownloadOutlined/>;
// // Modal實現拖動效果
// class BuildTitle extends React.Component {
//     updateTransform = transformStr => {
//         this.modalDom.style.transform = transformStr;
//     };
//     componentDidMount() {
//         this.modalDom = document.getElementsByClassName(
//             "ant-modal-wrap" //modal的class是ant-modal-wrap
//         )[0];
//     }
//     render() {
//         const { title } = this.props;
//         return (
//             <DragM updateTransform={this.updateTransform}>
//                 <div>{ title }</div>
//             </DragM>
//         );
//     }
// }

let config = require("../../util/config").config

export default class ModuleManage extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            current:1,
            count:null,
            data:[],
            spinFlag:false,
            pageSize:10,
            selectedRowKeys: [], // Check here to configure the default column
            moduleInsertVisible:false,
            moduleUpdateVisible:false,
            moduleContentVisible:false,
            fileInsertVisible:false,
            fileUpdateVisible:false,
            fileContent:null,
            fileList:[],
            name: null,
            type: null,
            // columns: this.columns
        };
        // this.storeFresh = this.storeFresh.bind(this)
        // store.subscribe(this.storeFresh)
        const result = API.getActivity();
        this.state.data = result.data;
        this.state.count = result.count;
    }

    status=false;

    data = null;
    searchKey = "";
    startDate = "";
    endDate = "";
    startDate2 = "";
    endDate2 = "";
    text = config.is_delete;

    columns = [
        {
            title: "配图",
            dataIndex: 'figure',
            key: 'type',
            fixed:"left",
            render:(text)=> <img src={text} style={{width:"80%"}}/>,
            width:this.props.type=="consumer" ?250:200
        },
        {
            title: "标题",
            dataIndex: 'name',
            key: 'name',
            fixed:"left",
            ellipsis:true,
            width:this.props.type=="consumer" ?300:280,
            render:(text,record) => {
                console.log("Component Activity Activity",this.props)
                let path = null;
                if(typeof(this.props.match) == "undefined"){
                    path = `/eip/file/activity/${record.key}`;
                }
                else if(this.props.match.path=="/eip/activity-manage"){
                    path = `/eip/activity-manage-content/${record.key}`;
                }
                return(
                    <Link to={path}>
                        {text}
                    </Link>
                )
            }
        },
        {
            title: '建立人',
            dataIndex:"createUser",
            ellipsis:true,
            key: 'Options',
            width:this.props.type=="consumer" ?210:150
        },
        {
            title: '建立时间',
            dataIndex:"createTime",
            ellipsis:true,
            key: 'Options',
            width:this.props.type=="consumer" ?210:150
        },
        {
            title: '修改人',
            dataIndex:"updateUser",
            ellipsis:true,
            key: 'Options',
            width:this.props.type=="consumer" ?210:150
        },
        {
            title: '修改时间',
            dataIndex:"updateTime",
            ellipsis:true,
            key: 'Options',
            width:this.props.type=="consumer" ?210:150
        },
        {
            title: "状态",
            dataIndex: 'status',
            key: 'status',
            width:this.props.type=="consumer" ?150:80,
            fixed:"right",
            render:(text,record)=>{
                return (
                    <span>
                        {this.isTop(text)}
                        {this.isNotify(record)}
                    </span>
                )
            }
        },
        this.props.type=="consumer"
            ?
        {}
            :
        {
            title: '操作',
            key: 'Options',
            width:200,
            fixed:"right",
            render: (text, record) => (
                <div>
                    <Button style={{marginRight:"0.5rem"}} type="primary" shape="round" size="middle" onClick={_=>{this.update(record)}}>
                        修改
                    </Button>
                    <Popconfirm placement="right" title={this.text} onConfirm={_=>{this.delete(record)}} okText="确定" cancelText="取消">
                        <Button type="primary" shape="round" style={{marginRight: "1rem", border: "0.1rem solid #ff7875"}} danger>
                            删除
                        </Button>
                    </Popconfirm>
                </div>
            ),
        },
    ]

    isTop = (text)=>{
        if(text=="Y"){
            return <Tag color="#f50">{config.top_status}</Tag>
        }
    }

    isNotify = (record)=>{
        let currentDate = new Date()
        let date = new Date(record.updateTime);
        if(record.new!="" && record.new!=null){
            date.setDate(date.getDate()+Number.parseInt(record.new));
            if(currentDate<=date){
                return <Tag color="#87d068">{config.new_notify}</Tag>
            }
        }
    }
    result=(result)=>{
        this.status = result;
    }

    insert = () =>{
        closeStatus();
        this.setState({moduleInsertVisible:true})
    }

    cancel = () => {
        closeStatus();
        this.setState({
            selectedRowKeys: [],
            loading: false
        });
    };

    delete = (record) => {
        if(API.deleteActivity([record.key])){
            let tmpData = API.getActivity(this.searchKey,this.startDate,this.endDate,this.state.current,this.state.pageSize);
            this.setState({
                data:tmpData.data,
                count:tmpData.count,
            })
        }
    }

    deleteSelect=()=>{
        if(API.deleteActivity(this.state.selectedRowKeys)){
            let tmpData = API.getActivity(this.searchKey,this.startDate,this.endDate,this.state.current,this.state.pageSize);
            this.setState({
                data:tmpData.data,
                count:tmpData.count
            });
        }
    }

    update = (record) => {
        closeStatus()
        this.data=record
        sessionStorage.setItem("index",JSON.stringify(record))
        this.setState({moduleUpdateVisible:true})
    }

    onSelectChange = selectedRowKeys => {
        closeStatus()
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
    };

    handleOk = () => {
        if(this.status==true){
            this.status=false
            let result = API.getActivity(this.searchKey,this.startDate,this.endDate,1,this.state.pageSize)
            this.setState({
                data:result.data,
                count:result.count,
                current:1
            });
        }
        this.setState({
            moduleInsertVisible: false,
            moduleUpdateVisible: false,
        });
    };

    onChange=(moment,string)=>{
        this.startDate=string[0];
        this.endDate=string[1];
        // this.getDataByCondition(this.searchKey,this.startDate,this.endDate);
    }

    //表单对象
    formRef = React.createRef();

    onReset = () => {
        this.formRef.current.resetFields();
    };

    onFinish = (item) =>{
        this.searchKey = item.activityName==undefined?"":item.activityName
        this.startDate2 = this.startDate
        this.endDate2 = this.endDate
        this.setState({spinFlag:true},()=>{
            setTimeout(()=>{
                let result = API.getActivity(this.searchKey,this.startDate2,this.endDate2,1,this.state.pageSize)
                this.setState({current:1,data:result.data,count:result.count,spinFlag:false})
            },100)
        })
        console.log(item)
    }

    onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
        this.changePage(1,pageSize)
        this.setState({pageSize:pageSize})
    }

    changePage(current,pageSize){
        console.log(current,pageSize);
        let searchKey = this.searchKey==""?null:this.searchKey;;
        let startDate = this.startDate2==""?null:this.startDate2;
        let endDate = this.endDate2==""?null:this.endDate2;
        let result = API.getActivity(searchKey,startDate,endDate,current,pageSize);
        this.setState({
            data:result.data,
            count:result.count,
            current:current
        });
    }

    paginationProps =_=> {
        const total = this.state.count
        const pageSize = this.state.pageSize
        return {
            current:this.state.current,
            showSizeChanger: true,//设置每页显示数据条数
            showQuickJumper: false,
            // showTotal: () => `共${this.state.count}条`,
            pageSize: pageSize,
            total: total,  //数据的总的条数
            onChange: (current) => this.changePage(current,pageSize), //点击当前页码
            onShowSizeChange: (current, pageSize) => {//设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
                console.log(pageSize);
                this.onShowSizeChange(current, pageSize)
            }
        }
    }

    render() {
        // console.log("Component Activity Activity",this.props)
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <Spin spinning={this.state.spinFlag}>
                <div style={{marginBottom:"1rem"}} >
                    {
                        this.props.type=="consumer" ?
                            null
                            :
                            <span style={{marginRight:"1rem"}}>
                                <Button type="primary" onClick={this.insert} style={{marginRight:"0.5rem"}}>
                                    添加
                                </Button>
                                <Button type="danger" onClick={this.deleteSelect} disabled={!hasSelected} style={{marginRight:"0.5rem"}}>
                                    删除选中
                                </Button>
                                <Button type="primary" onClick={this.cancel} disabled={!hasSelected}>
                                    取消
                                </Button>
                                <span style={{ marginLeft: 8 }}>
                                    {hasSelected ? `已選中 ${selectedRowKeys.length} 筆數據` : ''}
                                </span>
                            </span>
                    }
                    <Form
                        ref={this.formRef}
                        onFinish={this.onFinish}
                        onReset={this.onReset}
                        style={{display:"inline"}}
                        layout={"inline"}
                    >
                        <Form.Item
                            name="accessNum"
                            label="活動記錄"
                            style={{display:"inline"}}
                        >
                            共{this.state.count}筆數據
                        </Form.Item>
                        <Form.Item
                            name="dateBorder"
                            label="時間範圍"
                            style={{display:"inline"}}
                        >
                            <RangePicker allowClear showTime style={{ width: 220 }} onChange={this.onChange}/>
                        </Form.Item>
                        <Form.Item
                            name="activityName"
                            label="活动名稱"
                            style={{display:"inline"}}
                        >
                            <Input allowClear style={{ width: 120 }}/>
                        </Form.Item>
                        <Form.Item
                            label="查詢"
                            name="commit"
                            style={{display:"inline"}}
                        >
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button htmlType="reset" style={{marginLeft:"1rem"}}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
                <Table className={this.props.type!="consumer" ? "decorate" : null} rowSelection={this.props.type!="consumer" ?rowSelection:null} columns={this.columns} dataSource={this.state.data} scroll={{x: '80vw',y:"70vh"}} pagination={this.paginationProps()}/>
                {/*{hasSelected ? null : this.storeFresh(rowSelection)}*/}
                <Modal visible={this.state.moduleInsertVisible}
                       title="添加活动"
                       onCancel={this.handleOk}
                       footer={[
                           <Button key="back" onClick={this.handleOk}>退出</Button>
                       ]}
                       width={1000}
                       destroyOnClose
                >
                    <InsertFormForActivity result={this.result}></InsertFormForActivity>
                </Modal>
                <Modal visible={this.state.moduleUpdateVisible}
                       title="修改活动"
                       onCancel={this.handleOk}
                       footer={[
                           <Button key="back" onClick={this.handleOk}>退出</Button>
                       ]}
                       width={1000}
                       destroyOnClose
                >
                    <UpdateFormForActivity data={this.data} result={this.result}></UpdateFormForActivity>
                </Modal>
            </Spin>
        );
    }
}








